import os
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn



class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """处理多线程HTTP请求"""

    def shutdown(self):
        """重写shutdown方法确保完全关闭"""
        self.socket.close()
        super().shutdown()


class SharedFileHandler(SimpleHTTPRequestHandler):
    """自定义文件处理器，支持上传"""

    def do_POST(self):
        """处理文件上传"""
        content_length = int(self.headers['Content-Length'])
        upload_data = self.rfile.read(content_length)

        content_disposition = self.headers['Content-Disposition']
        filename_start = content_disposition.find('filename="') + 10
        filename_end = content_disposition.find('"', filename_start)
        filename = content_disposition[filename_start:filename_end]

        upload_dir = os.path.join(os.getcwd(), 'shared_files')
        os.makedirs(upload_dir, exist_ok=True)
        filepath = os.path.join(upload_dir, filename)

        # 更新上传进度
        self.server.app.root.after(0, lambda: self.server.app.update_upload_progress(filename, content_length))

        with open(filepath, 'wb') as f:
            f.write(upload_data)

        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'File uploaded successfully')